<template>
  <div>
    <Header>
      <template #right>
        <div class="flex items-center bg-[#fafbfc] rounded-[1.5rem] h-[3rem] w-[17.5rem] py-[1rem] px-[2rem] relative">
          <input 
            v-model="keyword" 
            type="text" 
            placeholder="搜索帖子、用户、标签..."
            class="flex-1 border-none outline-none bg-transparent text-[1rem] text-[#9CA3AF] placeholder:text-[#9CA3AF] placeholder:text-[1rem]"
            @input="handleInput"
            @keyup.enter="onSearch"
            @focus="showSuggestions = true"
            @blur="hideSuggestionsDelayed"
          />
          <img 
            src="/icon/search.png" 
            class="w-[1rem] h-[1rem] cursor-pointer ml-2" 
            @click="onSearch" 
          />
          
          <!-- 搜索建议下拉菜单 -->
          <div 
            v-if="showSuggestions && suggestions.length > 0" 
            class="absolute top-[3.25rem] left-0 w-full bg-white rounded-[0.5rem] shadow-md z-10 max-h-[20rem] overflow-y-auto"
          >
            <div 
              v-for="(suggestion, index) in suggestions" 
              :key="index"
              class="px-[1rem] py-[0.75rem] hover:bg-[#F9FAFB] cursor-pointer text-[0.875rem] border-b border-[#F3F4F6] last:border-b-0"
              @mousedown.prevent="selectSuggestion(suggestion)"
            >
              <div class="flex items-center">
                <span>{{ suggestion.text }}</span>
              </div>
            </div>
          </div>
        </div>
      </template>
    </Header>

    <div class="w-[80rem] mx-auto pt-[2rem] pb-[4rem]">
      <!-- 搜索结果标签栏 -->
      <div class="mb-[1.5rem] border-b border-[#F3F4F6]">
        <div class="flex items-center">
          <div 
            v-for="tab in tabs" 
            :key="tab.value"
            class="px-[1.5rem] py-[1rem] cursor-pointer text-[1rem] font-[Inter] font-medium"
            :class="activeTab === tab.value ? 'text-[#000] border-b-2 border-[#000]' : 'text-[#6B7280]'"
            @click="handleTabChange(tab.value)"
          >
            {{ tab.name }}
            <span v-if="tab.count !== undefined" class="ml-[0.25rem] text-[#9CA3AF]">({{ tab.count }})</span>
          </div>
        </div>
      </div>

      <!-- 精准匹配的用户结果 -->
      <div v-if="activeTab === 'all' && exactUserMatches.length > 0" class="mb-[2rem]">
        <!-- <div class="text-[1.25rem] font-bold mb-[1rem]">用户</div> -->
        <div class="flex overflow-x-auto pb-[1rem] gap-[1.5rem]">
          <div 
            v-for="user in exactUserMatches" 
            :key="user.id"
            class="flex-shrink-0 w-[12rem] flex flex-col items-center p-[1rem] border border-[#F3F4F6] rounded-[0.5rem] cursor-pointer hover:shadow-sm"
            @click="navigateToUser(user.id)"
          >
            <img :src="user.avatar" class="w-[4rem] h-[4rem] rounded-full mb-[0.5rem]" />
            <div class="font-medium text-center">{{ user.name }}</div>
            <div class="text-[0.875rem] text-[#6B7280] mt-[0.25rem] text-center">{{ user.bio }}</div>
            <div class="mt-[0.5rem] text-[0.75rem] text-[#9CA3AF]">{{ user.followers }} 关注者</div>
          </div>
        </div>
        <div class="border-b border-[#F3F4F6] my-[1.5rem]"></div>
      </div>

      <!-- 搜索结果列表 -->
      <div>
        <!-- 用户标签页 -->
        <div v-if="activeTab === 'users'" class="grid grid-cols-2 gap-[1.5rem]">
          <div 
            v-for="user in displayedUsers" 
            :key="user.id"
            class="flex items-start p-[1.5rem] border border-[#F3F4F6] rounded-[0.5rem] cursor-pointer hover:shadow-sm"
            @click="navigateToUser(user.id)"
          >
            <img :src="user.avatar" class="w-[4rem] h-[4rem] rounded-full" />
            <div class="ml-[1rem] flex-1">
              <div class="font-medium">{{ user.name }}</div>
              <div class="text-[0.875rem] text-[#6B7280] mt-[0.25rem]">{{ user.bio }}</div>
              <div class="mt-[0.5rem] text-[0.75rem] text-[#9CA3AF]">{{ user.followers }} 关注者</div>
            </div>
          </div>
        </div>

        <!-- 帖子标签页 -->
        <div v-else-if="activeTab === 'posts' || activeTab === 'all'">
          <ArticleCard 
            v-for="post in displayedPosts" 
            :key="post.id" 
            :article="post"
            class="mb-[1.5rem]"
          />
        </div>

        <!-- 话题标签页 -->
        <div v-else-if="activeTab === 'topics'" class="grid grid-cols-3 gap-[1.5rem]">
          <div 
            v-for="topic in displayedTopics" 
            :key="topic.id"
            class="flex flex-col items-center p-[1.5rem] border border-[#F3F4F6] rounded-[0.5rem] cursor-pointer hover:shadow-sm"
            @click="navigateToTopic(topic.id)"
          >
            <div class="px-[1rem] py-[0.5rem] bg-[#F9FAFB] rounded-[0.25rem] mb-[1rem]">
              {{ topic.name }}
            </div>
            <div class="text-[0.875rem] text-[#6B7280] text-center">{{ topic.description }}</div>
            <div class="mt-[1rem] text-[0.75rem] text-[#9CA3AF]">{{ topic.postCount }} 篇内容</div>
          </div>
        </div>

        <!-- 加载中提示 -->
        <div v-if="loading" class="py-[2rem] flex justify-center">
          <div class="flex items-center">
            <div class="animate-spin rounded-full h-[1.5rem] w-[1.5rem] border-t-2 border-b-2 border-[#000] mr-[0.5rem]"></div>
            <span>加载中...</span>
          </div>
        </div>

        <!-- 无搜索结果 -->
        <div v-if="noResults" class="py-[4rem] flex flex-col items-center">
          <!-- <img src="/icon/no-results.png" class="w-[8rem] h-[8rem] mb-[1.5rem]" /> -->
          <div class="text-[1.25rem] font-medium mb-[0.5rem]">暂无搜索结果</div>
          <div class="text-[1rem] text-[#6B7280]">
            未找到与"{{ keyword }}"相关的{{ tabNameMap[activeTab as keyof typeof tabNameMap] }}，请尝试其他关键词
          </div>
        </div>
      </div>
    </div>

    <Footer mode="dark"></Footer>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import Header from '@/components/Header/index.vue'
import Footer from '@/components/Footer/index.vue'
import ArticleCard from '@/components/ArticleCard/index.vue'

// 类型定义
interface Suggestion {
  id: number
  text: string
  type: 'post' | 'user' | 'topic'
}

interface User {
  id: number
  name: string
  avatar: string
  bio: string
  followers: number
}

interface Post {
  id: number
  author: string
  authorAvatar: string
  authorLevel: string
  title: string
  description: string
  releaseTime: string
  comment: number
  like: number
  collect: number
  tags: string[]
  showComment?: boolean
}

interface Topic {
  id: number
  name: string
  description: string
  postCount: number
}

// 路由相关
const route = useRoute()
const router = useRouter()

// 搜索相关
const keyword = ref('')
const showSuggestions = ref(false)
const suggestions = ref<Suggestion[]>([])
let debounceTimer: number | null = null
let blurTimer: number | null = null

// 标签页相关
const tabs = ref([
  { name: '综合', value: 'all', count: undefined },
  { name: '用户', value: 'users', count: 0 },
  { name: '帖子', value: 'posts', count: 0 },
  { name: '话题', value: 'topics', count: 0 }
])
const activeTab = ref('all')
const tabNameMap = {
  all: '内容',
  users: '用户',
  posts: '帖子',
  topics: '话题'
}

// 数据加载相关
const loading = ref(false)
const page = ref(1)
const pageSize = ref(10)
const hasMore = ref(true)

// 搜索结果
const users = ref<User[]>([])
const posts = ref<Post[]>([])
const topics = ref<Topic[]>([])

// 计算属性
const displayedUsers = computed(() => users.value)
const displayedPosts = computed(() => posts.value)
const displayedTopics = computed(() => topics.value)
const exactUserMatches = computed(() => {
  if (activeTab.value !== 'all') return []
  return users.value.slice(0, 5)
})
const noResults = computed(() => {
  if (loading.value) return false
  
  switch (activeTab.value) {
    case 'all':
      return users.value.length === 0 && posts.value.length === 0 && topics.value.length === 0
    case 'users':
      return users.value.length === 0
    case 'posts':
      return posts.value.length === 0
    case 'topics':
      return topics.value.length === 0
    default:
      return false
  }
})

// 初始化
onMounted(() => {
  // 从URL获取搜索关键词
  const queryKeyword = route.query.keyword as string
  const queryTag = route.query.tag as string
  
  if (queryKeyword) {
    keyword.value = queryKeyword
    search()
  } else if (queryTag) {
    keyword.value = queryTag
    activeTab.value = 'topics'
    search()
  }
  
  // 添加滚动监听
  window.addEventListener('scroll', handleScroll)
})

onUnmounted(() => {
  // 移除滚动监听
  window.removeEventListener('scroll', handleScroll)
  
  // 清除所有定时器
  if (debounceTimer) {
    clearTimeout(debounceTimer)
  }
  if (blurTimer) {
    clearTimeout(blurTimer)
  }
})

// 方法
function handleTabChange(tab: string) {
  if (activeTab.value === tab) return
  
  activeTab.value = tab
  
  // 重置页码，但不清空已有数据
  page.value = 1
  
  // 如果当前标签页还没有数据，则加载数据
  if ((tab === 'all' && users.value.length === 0 && posts.value.length === 0 && topics.value.length === 0) ||
      (tab === 'users' && users.value.length === 0) ||
      (tab === 'posts' && posts.value.length === 0) ||
      (tab === 'topics' && topics.value.length === 0)) {
    hasMore.value = true
    search()
  }
  
  // 滚动到顶部
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

function handleInput() {
  // 清除之前的定时器
  if (debounceTimer) {
    clearTimeout(debounceTimer)
  }
  
  // 设置新的定时器，300ms后执行搜索
  debounceTimer = window.setTimeout(() => {
    if (keyword.value.trim()) {
      suggestions.value = mockSuggestions(keyword.value)
    } else {
      suggestions.value = []
    }
  }, 300)
}

function onSearch() {
  if (!keyword.value.trim()) return
  
  // 清空建议
  suggestions.value = []
  showSuggestions.value = false
  
  // 更新URL
  router.push({
    path: '/forum/search',
    query: { keyword: keyword.value }
  })
  
  // 重置搜索并执行
  resetSearch()
  search()
}

function hideSuggestionsDelayed() {
  // 延迟隐藏下拉菜单，让点击事件有时间触发
  blurTimer = window.setTimeout(() => {
    showSuggestions.value = false
  }, 200)
}

function selectSuggestion(suggestion: Suggestion) {
  // 根据类型执行不同的操作
  switch (suggestion.type) {
    case 'post':
      router.push(`/forum/details/${suggestion.id}`)
      break
    case 'user':
      router.push(`/user/${suggestion.id}`)
      break
    case 'topic':
      router.push(`/forum/search?tag=${encodeURIComponent(suggestion.text)}`)
      break
  }
  
  // 关闭建议下拉框
  showSuggestions.value = false
}

function navigateToUser(userId: number) {
  router.push(`/user/${userId}`)
}

function navigateToTopic(topicId: number) {
  router.push(`/forum/topic/${topicId}`)
}

function resetSearch() {
  page.value = 1
  hasMore.value = true
  
  // 只清空当前标签页相关的结果
  if (activeTab.value === 'all') {
    users.value = []
    posts.value = []
    topics.value = []
  } else if (activeTab.value === 'users') {
    users.value = []
  } else if (activeTab.value === 'posts') {
    posts.value = []
  } else if (activeTab.value === 'topics') {
    topics.value = []
  }
}

function search() {
  if (loading.value || !hasMore.value) return
  
  loading.value = true
  
  // 模拟API调用延迟
  setTimeout(() => {
    // 模拟获取搜索结果
    const newResults = mockSearchResults(keyword.value, activeTab.value, page.value, pageSize.value)
    
    // 更新数据，只更新当前标签页所需的数据
    if (activeTab.value === 'all') {
      // 综合标签页加载所有类型数据
      users.value = page.value === 1 ? newResults.users : [...users.value, ...newResults.users]
      posts.value = page.value === 1 ? newResults.posts : [...posts.value, ...newResults.posts]
      topics.value = page.value === 1 ? newResults.topics : [...topics.value, ...newResults.topics]
      
      // 更新计数
      tabs.value[1].count = newResults.userTotal
      tabs.value[2].count = newResults.postTotal
      tabs.value[3].count = newResults.topicTotal
    } else if (activeTab.value === 'users') {
      // 只加载用户数据
      users.value = page.value === 1 ? newResults.users : [...users.value, ...newResults.users]
      tabs.value[1].count = newResults.userTotal
    } else if (activeTab.value === 'posts') {
      // 只加载帖子数据
      posts.value = page.value === 1 ? newResults.posts : [...posts.value, ...newResults.posts]
      tabs.value[2].count = newResults.postTotal
    } else if (activeTab.value === 'topics') {
      // 只加载话题数据
      topics.value = page.value === 1 ? newResults.topics : [...topics.value, ...newResults.topics]
      tabs.value[3].count = newResults.topicTotal
    }
    
    // 更新页码和是否有更多数据
    page.value += 1
    hasMore.value = newResults.hasMore
    
    loading.value = false
  }, 800)
}

function handleScroll() {
  // 计算是否滚动到底部
  const scrollPosition = window.scrollY + window.innerHeight
  const documentHeight = document.documentElement.scrollHeight
  
  // 当距离底部200px时加载更多
  if (scrollPosition >= documentHeight - 200 && !loading.value && hasMore.value) {
    search()
  }
}

// 模拟搜索建议API
function mockSuggestions(query: string): Suggestion[] {
  if (!query) return []
  
  const mockData: Suggestion[] = [
    { id: 1, text: `前端${query}学习指南`, type: 'post' },
    { id: 2, text: `如何掌握${query}技巧`, type: 'post' },
    { id: 3, text: `${query}精选`, type: 'topic' },
    { id: 4, text: `${query}专家`, type: 'user' },
    { id: 5, text: `${query}问题解决方案`, type: 'post' }
  ]
  
  return mockData.filter(item => 
    item.text.toLowerCase().includes(query.toLowerCase())
  )
}

// 模拟搜索结果API
function mockSearchResults(query: string, tab: string, page: number, pageSize: number) {
  const maxPage = 3
  const hasMore = page < maxPage
  
  // 模拟用户结果
  const users: User[] = []
  if (tab === 'all' || tab === 'users') {
    for (let i = 1; i <= pageSize; i++) {
      if (page > maxPage) break
      const id = (page - 1) * pageSize + i
      users.push({
        id,
        name: `${query}用户${id}`,
        avatar: '/public/images/avatar.png',
        bio: `我是一名${query}爱好者，擅长分享${query}相关内容。`,
        followers: Math.floor(Math.random() * 1000) + 10
      })
    }
  }
  
  // 模拟帖子结果
  const posts: Post[] = []
  if (tab === 'all' || tab === 'posts') {
    for (let i = 1; i <= pageSize; i++) {
      if (page > maxPage) break
      const id = (page - 1) * pageSize + i
      posts.push({
        id,
        author: `作者${id}`,
        authorAvatar: '/public/images/avatar.png',
        authorLevel: Math.floor(Math.random() * 10).toString(),
        title: `关于${query}的探讨(${id})`,
        description: `这篇文章主要讨论了${query}的相关内容，包括如何学习和应用${query}技术。`,
        releaseTime: '2小时前',
        comment: Math.floor(Math.random() * 100),
        like: Math.floor(Math.random() * 200),
        collect: Math.floor(Math.random() * 50),
        tags: [`${query}`, '技术', '讨论']
      })
    }
  }
  
  // 模拟话题结果
  const topics: Topic[] = []
  if (tab === 'all' || tab === 'topics') {
    for (let i = 1; i <= pageSize; i++) {
      if (page > maxPage) break
      const id = (page - 1) * pageSize + i
      topics.push({
        id,
        name: `${query}话题${id}`,
        description: `这是关于${query}的话题，包含了大量相关讨论和资源。`,
        postCount: Math.floor(Math.random() * 1000) + 50
      })
    }
  }
  
  return {
    users,
    posts,
    topics,
    userTotal: 56,
    postTotal: 128,
    topicTotal: 32,
    hasMore
  }
}
</script>

<style scoped>
.animate-spin {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>